package store.swing.product;

import store.domain.Product;
import store.util.AppUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;


public class ProductPanel extends JPanel {
    private JTextField searchField;
    private JButton updateDataButton;
    private ProductTable productTable;

    public ProductPanel() {
        initComponents();
    }

    private void initComponents() {
        setLayout(new GridBagLayout());
        ((GridBagLayout) getLayout()).columnWidths = new int[]{0, 0, 0, 0};
        ((GridBagLayout) getLayout()).rowHeights = new int[]{35, 0, 0};
        ((GridBagLayout) getLayout()).columnWeights = new double[]{0.0, 1.0, 0, 1.0E-4};
        ((GridBagLayout) getLayout()).rowWeights = new double[]{0.0, 1.0, 0, 1.0E-4};

        GridBagConstraints c = new GridBagConstraints();
        c.insets = new Insets(5, 5, 5, 5);
        c.fill = GridBagConstraints.BOTH;

        JLabel searchLabel = new JLabel("Search:");
        c.gridx = 0;
        c.gridy = 0;
        add(searchLabel, c);

        searchField = new JTextField();
        searchField.addKeyListener(new SearchListener());
        c.gridx = 1;
        c.gridy = 0;
        add(searchField, c);

        updateDataButton = new JButton("Обновить данные");
        updateDataButton.addActionListener(new UpdateDataButtonListener());
        c.gridx = 2;
        c.gridy = 0;
        add(updateDataButton, c);

        productTable = new ProductTable();
        JScrollPane scrollPane = new JScrollPane(productTable);
        c.gridx = 0;
        c.gridy = 1;
        c.gridwidth = 3;
        add(scrollPane, c);
    }

    private class UpdateDataButtonListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            java.util.List<Product> products = AppUtils.getService("productService").readAll();
            ProductTableModel.setProducts(products);
            ProductTable.getTableModel().fireTableDataChanged();
        }
    }

    private class SearchListener extends KeyAdapter {
        @Override
        public void keyReleased(KeyEvent e) {
            String text = searchField.getText();
            if (text.length() == 0) {
                productTable.getSorter().setRowFilter(null);
            } else {
                productTable.getSorter().setRowFilter(RowFilter.regexFilter(text));
            }
        }
    }
}
